import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'
const Layout = () => import('@/views/layout')
const Home = () => import('@/views/home')
const Question = () => import('@/views/question')
const Video = () => import('@/views/video')
const Profile = () => import('@/views/profile')

const Login = () => import('@/views/login')

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    // 布局骨架
    component: Layout,
    children: [
      {
        path: '/',
        component: Home,
        meta: {
          isKeepAlive: true
        }
      },
      {
        path: '/question',
        component: Question
      },
      {
        path: '/video',
        component: Video
      },
      {
        path: '/user',
        component: Profile
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/user/chat',
    component: () => import('@/views/user/chat.vue')
  },
  {
    path: '/search/result',
    component: () => import('@/views/search/results.vue')

  },
  {
    path: '/article/:id',
    name: 'article',
    component: () => import('@/views/article'),
    meta: {
      isKeepAlive: true
    }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const { user } = store.state
  // 以user开头的页面必须带token访问 没有就跳转登陆页面 并且带着将要访问的页面
  if (to.path.startsWith('/user') && !user.token) {
    next('/login?redirectUrl=' + to.path)
  } else {
    next()
  }
})

export default router
